package cn.com.majiang.controller;

import cn.com.majiang.domain.Manager;
import cn.com.majiang.enums.ResultCode;
import cn.com.majiang.param.ManagerParam;
import cn.com.majiang.result.BaseResult;
import cn.com.majiang.service.IManagerService;
import cn.com.majiang.service.IResourcesService;
import cn.com.majiang.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.google.code.kaptcha.Producer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jiangyanxin on 2017/5/28.
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
public class LoginController {
    Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    IManagerService managerService;
    @Autowired
    IResourcesService resourcesService;
    @Autowired
    private Producer captchaProducer = null;

    @Value("#{sys['webdomain']}")
    private String webdomain;

    /**
     * 后台登录
     *
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public BaseResult login(HttpServletRequest request,HttpServletResponse response, String checkcode,String remember, String username, String password) {
        logger.info("登录参数" + username + password);
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password) ) {
            return BaseResult.build(ResultCode.NULL_REQUESTPARAM);
        }
        //验证码判断
      /*  String imageCode = request.getSession().getAttribute("imagecode")+"";
        if(!checkcode.toUpperCase().equals(imageCode.toUpperCase())){
            return BaseResult.build(ResultCode.REQUEST_PARAM_ERROR);
        }*/
        Manager manager = managerService.selectManagerByUsername(username);
        if (manager != null && StringUtil.MD5(password).equals(manager.getPassword())) {
            logger.info("登录成功");
            //登录成功 用户信息放入缓存
            HttpSession session = request.getSession();
            session.setAttribute("manager", manager);
            session.setAttribute("actualCard", manager.getActualcard());
            session.setAttribute("totalCards", manager.getTotalcards());
            session.setAttribute("tel", manager.getTelephone());
            session.setAttribute("name", manager.getName());
            session.setAttribute("type", manager.getPowerId());
            session.setAttribute("id", manager.getId());
            logger.info("remember"+remember);
            Cookie cookie2 = new Cookie("username", username);
            Cookie cookie3 = new Cookie("password",password);
            cookie2.setPath("/");
            cookie3.setPath("/");
            cookie2.setMaxAge(7*24*3600);
            cookie3.setMaxAge(7*24*3600);
            cookie2.setDomain(webdomain);
            cookie3.setDomain(webdomain);
            response.addCookie(cookie3);
            response.addCookie(cookie2);
            if(StringUtils.isNotBlank(remember) &&"1".equals(remember)){
                Cookie cookie1 = new Cookie("remember","1");
                cookie1.setPath("/");
                cookie1.setMaxAge(7*24*3600);
                cookie1.setDomain(webdomain);
                response.addCookie(cookie1);

            }
            logger.info("session"+session.getAttribute("type"));
            return BaseResult.build(ResultCode.REQUEST_SUCCESS);
        }
        return BaseResult.build(ResultCode.REQUEST_FAIL);
    }

    @RequestMapping(value = "/getMenus", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public BaseResult getMenus( HttpServletRequest request)
            throws Exception {
        HttpSession session = request.getSession();
        logger.info("session"+session.getAttribute("type"));
        Integer type = (Integer) session.getAttribute("type");
        if (type == null) {
            return BaseResult.build(ResultCode.NULL_REQUESTPARAM);
        }
        List<Map<String, String>> list = resourcesService.getResourcesByPowerId(type);
        Map map = new HashMap();
        map.put("menus", list);
        BaseResult result = BaseResult.build(map);
        logger.info("返回结果" + JSON.toJSONString(result));
        return result;
    }

    @RequestMapping(value = "/checkPassword", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public BaseResult checkpassword(@RequestParam String password, HttpServletRequest request)
            throws Exception {
        logger.info("校验密码,password{}", password);
        if (StringUtils.isBlank(password)) {
            return BaseResult.build(ResultCode.NULL_REQUESTPARAM);
        }
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("name");

        if (StringUtils.isBlank(username)) {
            return BaseResult.build(ResultCode.REQUEST_PARAM_ERROR);
        }
        Manager manager = managerService.selectManagerByUsername(username);
        if (manager != null && StringUtil.MD5(password).equals(manager.getPassword())) {
            return BaseResult.build(ResultCode.REQUEST_SUCCESS);
        } else {
            return BaseResult.build(ResultCode.REQUEST_FAIL);
        }
    }

    /**
     * 超管修改代理商密码
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/updatePassword")
    @ResponseBody
    public BaseResult updateManagerPwd(HttpServletRequest request, String str, HttpServletResponse response) {
        HttpSession session = request.getSession();
        Manager manager = (Manager) session.getAttribute("manager");
        if (manager != null) {
            if (StringUtils.isBlank(str)) {
                logger.info("参数为空");
                return BaseResult.build(ResultCode.NULL_REQUESTPARAM);
            }
            ManagerParam param = JSON.parseObject(str, ManagerParam.class);
            if (StringUtils.isBlank(param.getOldPass()) && StringUtils.isBlank(param.getNewPass()) || StringUtils.isBlank(param.getNewPass2())) {
                logger.info("参数为空");
                return BaseResult.build(ResultCode.NULL_REQUESTPARAM);
            }
            if (!param.getNewPass().equals(param.getNewPass2())) {
                logger.info("新密码两次输入值不一致");
                return BaseResult.build(ResultCode.REQUEST_PARAM_ERROR);
            }
            param.setId(manager.getId());
            param.setNewPass(StringUtil.MD5(param.getNewPass()));
            if (managerService.updateManagerInfo(param) > 0) {
                return BaseResult.build(ResultCode.REQUEST_SUCCESS);
            }

        }
        return BaseResult.build(ResultCode.REQUEST_FAIL);
    }

    @RequestMapping("/imageCode")
    public ModelAndView getKaptchaImage(HttpServletRequest request,
                                        HttpServletResponse response) throws Exception {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control",
                "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        String capText = captchaProducer.createText();
        HttpSession session = request.getSession();
        session.setAttribute("imagecode", capText);
        logger.info("imagecode{}",capText);
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }

    /**
     * 退出登录
     * @param request
     * @param response
     */
    @RequestMapping("/logout ")
    @ResponseBody
    public BaseResult logout(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        if(session != null){
            session.invalidate();
        }
        return BaseResult.build(ResultCode.REQUEST_SUCCESS);

    }


}
